package com.jt.consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ConsumerController {
    @Autowired  //属性注入(但是属性不能使用final修饰)
    private RestTemplate restTemplate;

    @Value("${server.port:8080}")
    private String serverPort;

    @GetMapping("/consumer/doRestEcho1")
    public String doRestEcho01(){
        String url="http://localhost:8081/provider/echo/{msg}";
        return restTemplate.getForObject(url,
                String.class,"8090");//String.class为rul对应服务的响应结果类型
    }

    @Autowired
    private LoadBalancerClient loadBalancerClient;



    @GetMapping("/consumer/doRestEcho2")
    public String doRestEcho02(){
        //1)基于服务名（这个名字是ncos注册中心的一个服务名）获取服务实例
        ServiceInstance serviceInstance = loadBalancerClient.choose("sca-provider");
        //2）基于服务实例构建远端服务url
        String url = String.format("http://%s:%s/provider/echo/%s",serviceInstance.getHost(),serviceInstance.getPort(),serverPort);
        System.out.println("request url:"+url);
        return restTemplate.getForObject(url, String.class);
    }

    @Autowired
    private RestTemplate loadBalancedRestTemplate;

    @GetMapping("/consumer/doRestEcho3")
    public String doRestEcho03(){
        String url="http://sca-provider/provider/echo/{msg}";
        return loadBalancedRestTemplate.getForObject(url, String.class,serverPort);
    }
}

